﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web;
using QDT.Common;
using QDT.Common.Data;
using QDT.Core;
using QDT.Core.Deals;
using QDT.Core.Members;
using QDT.Core.Projects;

namespace QDT.Web.Admin.Code
{
    public class PointHelper
    {

        public void ProjectPointSta(int pid)
        {

            Thread.Sleep(1000);
            var db = IoC.Resolve<IUnitOfWork>() as IDbProvider;
            if (db == null) throw new Exception("数据库连接异常");

            var project = db.GetByID<Project>(pid);

            if (project == null || project.AssignAble)
            {
                return;
            }

            var credits = db.D<Credit>().Where(x => x.ProjectID == pid && x.AssignmentID == 0);
            foreach (var credit in credits)
            {
                var user = db.GetByID<User>(credit.UserID);
                user.UserAccount.Point += Convert.ToInt32(credit.BuyMoney);

                var log = new UserTransLog(user.ID, UserTransLog.TradeType.Other, 0, user.UserAccount.Money)
                {
                    Info = "投资获积分 : " + credit.BuyMoney.ToString("0")
                };
                db.Add(log);

                if (!credit.Equals(credits.FirstOrDefault(x=>x.UserID==credit.UserID))) continue;

                var hascredit = db.D<Credit>().Any(x => x.UserID == user.ID && x.InnerStatus > 2 && x.ProjectID != credit.ProjectID);
                if (hascredit) continue;

                var puser = db.GetByID<User>(user.RecommendID);
                if (puser == null) continue;

                puser.UserAccount.Point += 10000;

                var plog = new UserTransLog(puser.ID, UserTransLog.TradeType.Other, 0, puser.UserAccount.Money)
                {
                    Info = "推荐获积分 : 10000 [ 用户：" + user.UserName +" ] "
                };
                db.Add(plog);

            }
            db.SaveChanges();
        }

    }
}